#include<iostream>
#include<unistd.h>

//防止僵尸进程处理方法
//使用信号量，
//步骤1、注册信号函数，子进程GG后，捕获子进程GG的信号，
//步骤2、在信号函数里，父进程调用wait或者waitpid即可

static void sig_handle(int);

int main(){
    //注册函数
    signal(SIGCHLD, sig_handle);

    pid_t childPid;
    childPid = fork();
    if(childPid < 0){
        printf("fork error\n");
        exit(0);
    }else if(childPid == 0){
        //child
        printf("im child, getpid()=%d\n", getpid());
        sleep(2);
        printf("im child after sleep, getpid()=%d\n", getpid());
    }else{
        signal(SIGCHLD, sig_handle);
        //parent
        sleep(10);
        printf("father exit, getpid()=%d\n", getpid());
        system("ps -o pid,ppid,state,tty,command | grep zombie_sig");
    }
    
    return 0;
}

static void sig_handle(int signo){
    if(signo == SIGCHLD){
        printf("!!!catch signo SIGCHLD!!!\n");
        int status;
        pid_t diePid;
        diePid = wait(&status);

        printf("PID : %d died!!!\n", diePid);
    }else{
        printf("catch signo error\n");
    }
}